package yu.com.time.calclator

import yu.com.time.toLocalDateTime
import yu.com.time.toTime
import yu.com.time.unit.TimeUnit
import yu.com.time.unit.TimeUnit.*
import java.sql.Time
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.temporal.ChronoUnit


/**
 * Time时间计算器
 * created zpf on 2018/10/23 0023
 * @param origTime 原始时间
 * @param unit     时间计算单位
 */
open class TimeCalculator(val origTime: Time, val unit: TimeUnit) : Calculator<TimeCalculator, java.util.Date>, Time(origTime.time) {

    /**jdk8本地时间*/
    private val localTime: LocalTime = origTime.toLocalTime()
    /**jdk8本地日期时间*/
    private val localDateTime: LocalDateTime = origTime.toLocalDateTime()

    override fun plus(addition: Long): TimeCalculator {
        val time = when (unit) {
            HOUR -> localTime.plusHours(addition).toTime()
            MINUTE -> localTime.plusMinutes(addition).toTime()
            SECOND -> localTime.plusSeconds(addition).toTime()
            MILLI -> Time(origTime.time + addition)
            NANO -> localTime.plusNanos(addition).toTime()
        }
        return TimeCalculator(time, unit)
    }

    override fun minus(subtraction: java.util.Date): Long {
        val refer = subtraction.toLocalDateTime()
        return when (unit) {
            HOUR -> refer.until(localDateTime, ChronoUnit.HOURS)
            MINUTE -> refer.until(localDateTime, ChronoUnit.MINUTES)
            SECOND -> refer.until(localDateTime, ChronoUnit.SECONDS)
            MILLI -> refer.until(localDateTime, ChronoUnit.MILLIS)
            NANO -> refer.until(localDateTime, ChronoUnit.NANOS)
        }
    }
}
